using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema; 
using XPathParser; 
using System.Xml.Linq; 
using System.Xml.XPath;

namespace CodeGenerationPipelineInterface
{
	[DebuggerDisplay("{ DebugInfo }")]
	public class Element : IXmlElement
	{
        private IXmlDocument document;
        private XNode node;
        private WSDLTypeMappedTo wSDLTypeMappedTo;
        private ManagedList<Attribute> attributes;
        private ManagedList<Operation> operations;
        private string name; 
        private const int unbounded = int.MaxValue;

		public Element(IXmlDocument document)
		{
           attributes = new ManagedList<Attribute>("Attributes", "Element.Attributes", 0, unbounded);
           operations = new ManagedList<Operation>("Operations", "Element.Operations", 0, unbounded);
            
            this.document = document;
		}

        public IXmlDocument Document 
        { 
            get
            {
                return document;
            }

            set
            {
                document = value;
            }
        }

		[XPathAttribute("/ElementBuild/Elements/Root/ChildElements/Element[@Name]")]
		[UseAttribute(XPathParser.Use.Required)]
		public string Name 
		{
            get
            {
			    return name;
            }

            set
            {
                name = value;
            }
		}

		[XPathAttribute("/ElementBuild/Elements/Root/TypeArguments/Source/WSDLTypeMappedTo")]
		[MaxOccursAttribute(1)]
		public WSDLTypeMappedTo WSDLTypeMappedTo
		{
			get
			{
				return wSDLTypeMappedTo;
			}
		}

		[XPathAttribute("/ElementBuild/Elements/Root/ChildElements/Element/Attributes/Attribute")]
		[MinOccursAttribute(0)]
		[MaxOccursAttribute(unbounded)]
 
		public ManagedList<Attribute> Attributes
		{
			get
			{
				return attributes;
			}
		}

		[XPathAttribute("/ElementBuild/Elements/Root/ChildElements/Element/Operations/Operation")]
		[MinOccursAttribute(0)]
		[MaxOccursAttribute(unbounded)]
 
		public ManagedList<Operation> Operations
		{
			get
			{
				return operations;
			}
		}

		public string ElementName
		{
			get
			{
				return "Element";
			}
		}

		public string DebugInfo
		{
			get
			{
				return "Element";
			}
		}

        public XNode Node
        {
            get
            {
                return node;
            }
        }

        public IEnumerable<string> CDataElements
        {
            get
            {
                var element = (XElement)node;

                return element.Nodes().Where(n => n is XCData).Cast<XCData>().Select(c => c.Value);
            }
        }

        public void Read(XNode node)
        {
            var elementNode = (XElement) node;
            var prefix = elementNode.GetPrefixOfNamespace(elementNode.Name.Namespace);

            // WSDLTypeMappedTo

            var elementWSDLTypeMappedTo = node.XPathSelectElement(prefix + ":WSDLTypeMappedTo", this.Document.NamespaceManager);
            if (elementWSDLTypeMappedTo != null)
            {
                var wSDLTypeMappedTo = new WSDLTypeMappedTo(this.Document);

                wSDLTypeMappedTo.Read(elementWSDLTypeMappedTo);

                this.wSDLTypeMappedTo  = wSDLTypeMappedTo;
            }

            // Attributes

            foreach (var elementAttribute in node.XPathSelectElements(prefix + ":Attributes" + "/" + prefix + ":Attribute", this.Document.NamespaceManager))
            {
                var attributes = new Attribute(this.Document);

                attributes.Read(elementAttribute);

                this.attributes.Add(attributes);
            }

            // Operations

            foreach (var elementOperation in node.XPathSelectElements(prefix + ":Operations" + "/" + prefix + ":Operation", this.Document.NamespaceManager))
            {
                var operations = new Operation(this.Document);

                operations.Read(elementOperation);

                this.operations.Add(operations);
            }


            // Name

            if (elementNode.Attributes().Any(a => a.Name.LocalName == "Name"))
            {
                name = elementNode.Attribute("Name").Value;
            }
            this.node = node;
        }

        public void Write(XNode parentNode, XNamespace elementNamespace)
        {
            var parentElement = (XElement)parentNode;
            var element = new XElement(elementNamespace + this.ElementName);

            parentElement.Add(element);

            // Name

            element.Add(new XAttribute("Name", this.Name.ToString()));

            var wSDLTypeMappedTo = this.WSDLTypeMappedTo;

            if (wSDLTypeMappedTo != null)
            {
                wSDLTypeMappedTo.Write(element, elementNamespace);
            }
            var attributesElement = new XElement(elementNamespace + "Attributes");

            element.Add(attributesElement);

            foreach (var attributes in this.Attributes)
            {
                attributes.Write(attributesElement, elementNamespace);
            }

            var operationsElement = new XElement(elementNamespace + "Operations");

            element.Add(operationsElement);

            foreach (var operations in this.Operations)
            {
                operations.Write(operationsElement, elementNamespace);
            }

        }

        public void Write(XDocument document, XmlNamespaceManager namespaces)
        {
            var namespaceAttributes = namespaces.Cast<string>().Where(s => !string.IsNullOrEmpty(s) && s != "xmlns" && s != "xml").Select(s => new XAttribute(XNamespace.Xmlns + s, XNamespace.Get(namespaces.LookupNamespace(s))));
            var element = new XElement(this.document.ElementNamespace + this.ElementName, namespaceAttributes.ToArray<object>());

            document.Add(element);

            var wSDLTypeMappedTo = this.WSDLTypeMappedTo;
            wSDLTypeMappedTo.Write(element, this.document.ElementNamespace);

            var attributesElement = new XElement(this.Document.ElementNamespace + "Attributes");

            element.Add(attributesElement);

            foreach (var attributes in this.Attributes)
            {
                attributes.Write(attributesElement, this.Document.ElementNamespace);
            }

            var operationsElement = new XElement(this.Document.ElementNamespace + "Operations");

            element.Add(operationsElement);

            foreach (var operations in this.Operations)
            {
                operations.Write(operationsElement, this.Document.ElementNamespace);
            }

        }

        public bool Validate(object sender, ValidationEventHandler handler)
        {
            var valid = true;
            WSDLTypeMappedTo wSDLTypeMappedTo = this.WSDLTypeMappedTo;
            wSDLTypeMappedTo.Validate(sender, (sender2, e) =>
            {
                handler(sender2, e);
                valid = false;
            });

            foreach (Attribute attributes in this.Attributes)
            {
                attributes.Validate(sender, (sender2, e) =>
                {
                    handler(sender2, e);
                    valid = false;
                });
			}

            foreach (Operation operations in this.Operations)
            {
                operations.Validate(sender, (sender2, e) =>
                {
                    handler(sender2, e);
                    valid = false;
                });
			}

            return valid;
        }
    }
}
